package com.qf.dao.impl;

import com.qf.dao.CartDao;
import com.qf.entity.Cart;
import com.qf.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author wgy
 * @version V1.0
 * @project gp12_xiaomi
 * @package com.qf.dao.impl
 * @description: ${TODO}
 * @date 2022/6/23 16:42
 */
public class CartDaoImpl implements CartDao {
    @Override
    public void insert(Cart cart) {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        Object[] params={cart.getId(),cart.getPid(),cart.getNum(),cart.getMoney()};
        try {
            qr.update("insert into tb_cart values(?,?,?,?);", params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public Cart selectByUidAndPid(Integer id, int pid)  {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        try {
            return qr.query("select * from tb_cart where id=? and pid=?", new BeanHandler<>(Cart.class),id,pid);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(Cart cart) {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        Object[] params={cart.getNum(),cart.getMoney(),cart.getId(),cart.getPid()};
        try {
            qr.update("update tb_cart set num=?,money=? where id=? and pid=?", params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Cart> selectByUid(Integer id) {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        try {
            return qr.query("select * from tb_cart where id=?", new BeanListHandler<>(Cart.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(Integer uid, int pid) {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        try {
            qr.update("delete from tb_cart where id=? and pid=?", uid,pid);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteByUid(Integer uid) {
        QueryRunner qr=new QueryRunner();
        Connection conn=DataSourceUtils.getConnection();
        try {
            qr.update(conn,"delete from tb_cart where id=?", uid);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            DataSourceUtils.closeAll(null, null, conn);
        }
    }
}
